﻿using System.Text.RegularExpressions;

namespace Crawsome
{
    static class RegexMaster
    {
        /// <summary>
        /// Validates a given URL
        /// </summary>
        /// <param name="URL">A web URL</param>
        /// <returns>True if URL is valid, else false.</returns>
        public static bool isValidURL(string URL)
        {
            Regex validURL = new Regex(@"^(?<protocol>http|https)://(?<domain>[\w\.]+)(?<path>/.*)?");
            return validURL.IsMatch(URL);
        }

        /// <summary>
        /// Gets all 'href' link from a string
        /// </summary>
        /// <param name="Web">A string represents a web response</param>
        /// <returns>String array with all links found</returns>
        public static string[] getAllLinks(string Web)
        {
            Regex getAllLinks = new Regex("href=[\"']([^\"^']*)[\"']");
            MatchCollection matches = getAllLinks.Matches(Web);

            string[] Links = MatchCollectionToStringArray(matches);
            
            return Links;
        }

        /// <summary>
        /// Converts MatchCollection to a string array
        /// </summary>
        /// <param name="Matches">A MatchCollection</param>
        /// <returns>String[] represents the MatchCollection</returns>
        private static string[] MatchCollectionToStringArray(MatchCollection Matches)
        {
            string[] StringsArray = new string[Matches.Count];
            for (int i = 0; i < StringsArray.Length; i++)
            {
                StringsArray[i] = Matches[i].Groups[1].Value;
            }

            return StringsArray;
        }
    }
}
